﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;

using Blog.TemplateEngine;

namespace Blog.TemplateViewEngine
{
	public class TemplateView
	{
		readonly Template mLayoutTemplate;
		readonly Template mViewTemplate;

		public TemplateView(Template viewTemplate, Template layoutTemplate)
		{
			mViewTemplate = viewTemplate;
			mLayoutTemplate = layoutTemplate;
		}

		public Template ViewTemplate
		{
			get { return mViewTemplate; }
		}

		public Template LayoutTemplate
		{
			get { return mLayoutTemplate; }
		}

        public string RenderView(ViewContext viewContext)
        {
            return RenderView(CreateContext(viewContext));
        }

		public string RenderView(Context context)
		{
			bool hasLayout = mLayoutTemplate != null;

			string viewContent = mViewTemplate.Render(context);

			if(hasLayout)
			{
                context["content_for_view"] = viewContent;
                return mLayoutTemplate.Render(context);
            }
            return viewContent;
        }

		private Context CreateContext(ViewContext viewContext)
		{
            Context context = new Context();
			IDictionary<string, object> viewDataEntries = viewContext.ViewData as IDictionary<string, object>;

			if(viewDataEntries != null)
			{
				foreach(KeyValuePair<string, object> entry in viewDataEntries)
				{
                    context[entry.Key] = entry.Value;
				}
			}
			else
			{
                context["viewdata"] = viewContext.ViewData;
			}

            context["Mvc.ViewContext"] = viewContext;

            return context;
		}
	}
}